<?php
namespace App\Services\Exchange;
use App\Model\Exchange as E;
use App\Model\Goods;
use App\Model\Usera;
use App\Model\IntegralLog;
use Illuminate\Support\Facades\DB;

class Exchange{
    /**
     * @param $goods_id 商品id
     * @param $num 兑换几个
     */
    public function exchange($goods_id,$num,$uid){
        //查询商品
        $goodsInfo = Goods::where('id',$goods_id)->first(['integral','goods_name'])->toArray();
        //查询用户个人积分
        $userInfo = Usera::where('id',$uid)->first(['integral'])->toArray();
        $userIntegral =  $userInfo['integral'];
        $integral =  $goodsInfo['integral'] ;
        //判断用户积分是否够用
        if(($integral*$num) >$userIntegral){
            return 'error';
        }
        //修改用户积分
        $arr['integral'] = $userIntegral-$integral*$num;
        //兑换记录入库
        $data['goods_id'] = $goods_id;
        $data['time'] = time();
        $data['num'] = $num;
        $data['status'] = 1;
        $data['uid'] = $uid;
        //积分日志入库
        $array['time'] = time();
        $array['desc'] = '兑换'.$goodsInfo['goods_name'];
        $array['uid'] = $uid;
        $array['aas'] = '-'.$integral*$num;
        //事务处理
        DB::beginTransaction();
        try{
            $res1 = Usera::where('id',$uid)->update($arr);
            $res2 = E::insertGetId($data);
            $res3 = IntegralLog::insertGetId($array);
            if($res1&&$res2&&$res3){
                DB::commit();
                return true;
            }
        }catch(\Exception $e){
            DB::rollBack();
            return false;
        }
    }

    /**
     * 兑换商品记录
     */
    public function exchangeLog($uid){
        $data =  E::join('goods','goods.id','exchange_log.goods_id')->where('uid',$uid)->get()->toArray();
        foreach($data as &$v){
            $v['time'] = date('Y-m-d H:m:s',$v['time']);
        }
        return $data;
    }
}